import React, { Component } from 'react';
import {
  Dimensions,
  Platform,
  NativeModules,
  DeviceInfo,
  StyleSheet,
  Image,
  Text,
  View,
  TextInput,
  PixelRatio,
  TouchableOpacity,
  AsyncStorage,
  DeviceEventEmitter
} from 'react-native';
var Common = require('./common');
import ImagePicker from 'react-native-image-picker';
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

// screen
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

const pixelRatio = PixelRatio.get();
const dismissKeyboard = require('dismissKeyboard');
const options = {
    title: '选择图片',
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '图片库',
    cameraType: 'back',
    mediaType: 'photo',
    videoQuality: 'high',
    durationLimit: 10,
    maxWidth: 600,
    maxHeight: 600,
    aspectX: 2,
    aspectY: 1,
    quality: 0.8,
    angle: 0,
    allowsEditing: false,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};

export default class SendWords extends Component<Props> {
  constructor(props){
    super(props);
    this.state = {
      iphonex:false,
      showCeng:false,
      str: '推荐',
      news:[{"title":"ssss"},{"title":"ssss"},],
      imgsrc:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1514356844477&di=7c57fde0860194258cbec5c2720e0cf5&imgtype=0&src=http%3A%2F%2Fwww.swkweike.com%2Fdata%2Fuploads%2F2015%2F05%2F26%2F20430804665564348adc669.png',
      picbox: [],
      content:'',
      attach_id:'|'
    };
  }
  static navigationOptions = {
      tabBarLabel: '资讯',
      tabBarIcon: ({focused}) => {
          if (focused) {
              return (
                  <Image style={[styles.bnavImg,{width:22,height:22}]} source={require('./images/zixun1.png')}/>
              );
          }
          return (
              <Image style={[styles.bnavImg,{width:22,height:22}]} source={require('./images/zixun.png')}/>
          );
      },
  };
  isIphoneX() {

    return (

        Platform.OS === 'ios' && 

        ((SCREEN_HEIGHT === X_HEIGHT && SCREEN_WIDTH === X_WIDTH) || 

        (SCREEN_HEIGHT === X_WIDTH && SCREEN_WIDTH === X_HEIGHT))

    )

}


  ifIphoneX () {
    var flag = this.isIphoneX();
    if (flag) {
  console.log('true')
        this.setState({
          iphonex:true
        })
    } else {
  console.log('false')
        this.setState({
          iphonex:false
        })
    }
  }


  login(){
    var _this = this;
    Common.ajaxPost(Common.url + 'login.php', function(res){
      if(res.code == "0000"){

      }
    }.bind(this), {verify:'08login',t:''});
  }

  toRegister(){
    this.props.navigation.navigate('Register')
  }
  toHome(){

    this.props.navigation.goBack()
  }
  changeTabs(str){
    this.setState({
      str:str,

    })
  }

  showImagePicker() {
    var _this = this;
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
                console.log('User cancelled image picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }

            else {
                console.log(response)
                var picbox = this.state.picbox;
                picbox.push(response);
                this.setState({
                  picbox:picbox
                })
                let formData = new FormData();//如果需要上传多张图片,需要遍历数组,把图片的路径数组放入formData中
                let file = {uri: response.uri, type: 'multipart/form-data', name: 'image.png'};   //这里的key(uri和type和name)不能改变,
                //formData.append("files",file);   //这里的files就是后台需要的key
                formData.append("Filename",response.fileName);
                formData.append("PHPSESSID",file);
                formData.append("cut",1);
                formData.append("attach_type",'feed_image');
                formData.append("width",120);
                formData.append("upload_type",'image');
                formData.append("thumb",1);
                formData.append("height",120);
                // formData.append("Filedata",file);
                formData.append("Upload",'Submit Query');
                var config = {
              		method: 'POST',
              		headers: {
              			'Accept': 'application/json',
              			'Content-Type':'multipart/form-data',
              			'credentials': 'include'
              		},
              		credentials: 'include',
                  body:formData,
              	}


              	fetch(Common.url + 'thinksns/index.php?app=widget&mod=Upload&act=save', config).then((response) => response.json()).then((res) => {
                  console.log(res)
                  if(res.status ==1){
                    var attach_id = _this.state.attach_id;
                    attach_id+=res.data.attach_id + '|';
                    _this.setState({
                      attach_id: attach_id
                    })
                  }
                })
            }
        });
    }
renderPic(news){
  return news.map(function (data, index) {
    return (
      <Image style={{width:82,height:82,marginRight:10,marginBottom:10}} source={{uri:data.uri}} />
    )
  })
}

  componentWillMount(){
    this.ifIphoneX();
    AsyncStorage.getItem('logindata').then((value)=>{
			console.log(JSON.parse(value))
			this.setState({
				userinfo:JSON.parse(value)
			})
		})
    AsyncStorage.getItem('cookie').then((value)=>{
			console.log(value)
			this.setState({
				cookie:value
			})
		})
    // console.log(this.props.navigation.state.params)
    // if(this.props.navigation.state.params.from){
    //   this.setState({
    //     from:this.props.navigation.state.params,
    //   })
    // }
  }
  postMsg(){
    var _this = this;
    var config = {
  		method: 'POST',
  		headers: {
  			'Accept': 'application/json',
  			'Content-Type': 'application/json',
  			'credentials': 'include',
        'Cookie': _this.state.cookie
  		},
  		credentials: 'include'
  	}
    var param = {
      body:_this.state.content,
      type: 'postimage',
      app_name: 'public',
      channel: '',
      content: '',
      attach_id: _this.state.attach_id == '|' ? '' : _this.state.attach_id,
      video_id: '',
      videourl: '',
      channel_id:'',
    }
  	if (param) {
  		config["body"] = JSON.stringify(param);
  	}

  	fetch(Common.url + 'thinksns/index.php?app=public&mod=Feed&act=PostFeed&is_ajax=1', config).then((response) => response.json()).then((res) => {
      console.log(res)
      if(res.status == 401){
        this.props.navigation.navigate('Login')
      }else if(res.status == 1){
        DeviceEventEmitter.emit('reloadHudong', 1);//添加广播
        this.props.navigation.goBack()
      }
    })
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.head}>
          <TouchableOpacity style={styles.toback} onPress={this.toHome.bind(this)}>
            <Text style={{fontSize:16,}}>返回</Text>
          </TouchableOpacity>
          <Text style={styles.headTitle}>发帖</Text>
          <TouchableOpacity style={styles.btnSend} onPress={this.postMsg.bind(this)}>
            <Text style={{fontSize:14,color:'#fff'}}>发布</Text>
          </TouchableOpacity>
        </View>
        <View style={{padding:20,}}>
          <TextInput
            style={{minHeight:100}}
            multiline={true}
            onChangeText={(text) => this.setState({
							content: text
						})}
            value={this.state.text}
            placeholder='我有故事，你有酒吗...'
          />
          <View style={styles.picbox}>
            {this.renderPic(this.state.picbox)}
          </View>
          <View style={{paddingTop:10}}>
            <TouchableOpacity onPress={this.showImagePicker.bind(this)}>
              <Image style={{width:82,height:82}} source={require('./images/tianjia.png')} />
            </TouchableOpacity>
          </View>

        </View>




      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    height:Common.screenHeight,
    backgroundColor: '#fff',
  },
  head:{
    height:50,
    width:Common.screenWidth,
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'center',
    backgroundColor:'#fff',
    borderBottomColor:'#dbdbdb',
    borderBottomWidth:1,
  },
  headTitle:{
    fontSize:16,
  },
  picbox:{
    flexDirection:'row',
    alignItems:'center',
  },
  toback:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'center',
    height:50,
    position:'absolute',
    left:20,
    top:0,
    fontSize:14,
  },
  btnSend:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'center',
    width:60,
    height:25,
    position:'absolute',
    right:20,
    top:12,
    backgroundColor:'#3c78ff',
    borderRadius:4,
  },
  bnav:{
    width:Common.screenWidth,
    height:50,
    position:'absolute',
    left:0,
    bottom:0,
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'center',
    backgroundColor:'#f4f5f8',
    borderTopColor:'#afafaf',
    borderTopWidth:1,
  },
  bnavItem:{
    flex:1,
    flexDirection:'column',
    alignItems:'center',
    justifyContent:'center'
  },
  bnavText:{
    textAlign:'center',
    paddingTop:5,
  },
  bnavImg:{
    margin:'auto'
  }
});
